package colthgame.app;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PorterDuff.Mode;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.SurfaceHolder;
import android.view.View;
import android.widget.Gallery;
import android.widget.AdapterView;

public class ClothgameView extends SurfaceView implements SurfaceHolder.Callback, AdapterView.OnItemClickListener
{
	public ClothgameView(Context context)
	{
		super(context);
	}

	public ClothgameView(Context context, AttributeSet att)
	{
		super(context, att);
	}

	public void Init()
	{
		m_SurfaceHolder.addCallback(this);
		ClothgameResourceMgr.GetInstance().Init(this);

		m_ClothgameViewDrawThread = new ClothgameViewDrawThread(this);

		ColthgameActivity act = (ColthgameActivity) getContext();
		m_Gallery = (Gallery) act.findViewById(R.id.gallery1);
		m_Gallery.setAdapter(new ImageAdapter(getContext()));
		m_Gallery.setOnItemClickListener(this);

		m_character = new Character();
		m_character.SetBitmap(ClothgameResourceMgr.GetInstance().GetBitmap(R.drawable.ek2_character));
		ItemMgr.GetInstance().SetCharacterWidth(m_character.GetWidth());
		ClothgameResourceMgr.GetInstance().CreateItem();

	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
	{
		// TODO Auto-generated method stub
		ItemMgr.GetInstance().surfaceChanged(width, height);

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder)
	{
		// TODO Auto-generated method stub
		m_ClothgameViewDrawThread.start();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder)
	{
		// TODO Auto-generated method stub
		m_ClothgameViewDrawThread.stop();
	}

	public void Render()
	{
		m_canvas = m_SurfaceHolder.lockCanvas();
		if (null == m_canvas)
			return;

		try
		{
			synchronized (m_SurfaceHolder)
			{
				m_canvas.drawColor(Color.TRANSPARENT, Mode.CLEAR);
				m_character.Render(m_canvas);
				ItemMgr.GetInstance().Render(m_canvas);
			}
		} finally
		{
			m_SurfaceHolder.unlockCanvasAndPost(m_canvas);
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event)
	{
		// TODO Auto-generated method stub
		ItemMgr.GetInstance().onTouchEvent(event, m_character);
		return true;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int _nposition, long arg3)
	{
		ItemMgr.GetInstance().onItemClick(_nposition);
	}

	private ClothgameViewDrawThread	m_ClothgameViewDrawThread;
	private SurfaceHolder			m_SurfaceHolder	= getHolder();
	private Canvas					m_canvas;
	private Character				m_character;
	private Gallery					m_Gallery;
}
